import { fabric } from 'fabric'

const deleteIcon = "data:image/svg+xml,%3C%3Fxml version='1.0' encoding='utf-8'%3F%3E%3C!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN' 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3E%3Csvg version='1.1' id='Ebene_1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' x='0px' y='0px' width='595.275px' height='595.275px' viewBox='200 215 230 470' xml:space='preserve'%3E%3Ccircle style='fill:%23F44336;' cx='299.76' cy='439.067' r='218.516'/%3E%3Cg%3E%3Crect x='267.162' y='307.978' transform='matrix(0.7071 -0.7071 0.7071 0.7071 -222.6202 340.6915)' style='fill:white;' width='65.545' height='262.18'/%3E%3Crect x='266.988' y='308.153' transform='matrix(0.7071 0.7071 -0.7071 0.7071 398.3889 -83.3116)' style='fill:white;' width='65.544' height='262.179'/%3E%3C/g%3E%3C/svg%3E"
export const useInitCanvas = (canvasRef, attrs) => {
  // 删除按钮
  const createDeleteIcon = () => {
    const dImg = document.createElement('img')
    dImg.src = deleteIcon
  
    const renderIcon = (icon) => {
      return (ctx, left, top, styleOverride, fabricObject) => {
        const size = 24
        ctx.save()
        ctx.translate(left, top)
        ctx.rotate(fabric.util.degreesToRadians(fabricObject.angle))
        ctx.drawImage(icon, -size / 2, -size / 2, size, size)
        ctx.restore()
      }
    }
    const handleDelete = (eventData, transform) => {
      console.log('mouseUpHandler', eventData, transform)
      const target = transform.target
      const canvas = target.canvas
      canvas.remove(target)
      canvas.requestRenderAll()
    }

    const deleteControl = new fabric.Control({
      x: 0.5,
      y: -0.5,
      offsetY: -32,
      cursorStyle: 'pointer',
      render: renderIcon(dImg),
      mouseUpHandler: handleDelete,
      cornerSize: 24
    })

    fabric.Object.prototype.controls.deleteControl  = deleteControl
  }

  // 鼠标点击元素操作
  const onMouseEvent = () => {
    // 点击获取元素边框填充等属性
    canvasRef.value.on("mouse:down", function(options) {
      if(options.target) {
        const { 
          fill = '#0066cc',
          stroke = '',
          strokeWidth = 0
        } = options.target
        attrs.value = {
          fill,
          stroke,
          strokeWidth
        }
        canvasRef.value.renderAll();
      }
    })
    // canvasRef.value.on("mouse:up", () => {})
    // canvasRef.value.on("mouse:move", () => {})
  }
  const setCanvasBg = (bg = 'rgba(255, 255, 255, 1)') => {
    canvasRef.value.backgroundColor = bg
  }

  // 初始化
  const initCanvas = () => {
    createDeleteIcon()
    setCanvasBg()
    onMouseEvent()
  }

  return {
    initCanvas
  }
}
